package com.atguigu.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.atguigu.commonutils.R;
import com.atguigu.servicebase.exceptionHandler.MyHandler;
import com.atguigu.vod.service.VodService;
import com.atguigu.vod.utils.ConstantVodUtils;
import com.atguigu.vod.utils.InitObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/vod/video")
public class VodController {

    @Autowired
    private VodService vodService;

    //1   上传视频到阿里云
    @PostMapping("uploadVideo")
    public R uplodaVideo(MultipartFile file){
        String videoId = vodService.uploadVideo(file);
        return R.ok().data("videoId",videoId);
    }

    //2   删除阿里云端的视频
    @DeleteMapping("{videoId}")
    public R deleteVideo(@PathVariable String videoId){

        String accessKeyId = ConstantVodUtils.KEY_ID;
        String accessKeySecret = ConstantVodUtils.KEY_SECRET;
        DefaultAcsClient client = null;
        try {
            client = InitObject.initVodClient(accessKeyId, accessKeySecret);
            DeleteVideoRequest request = new DeleteVideoRequest();
            request.setVideoIds(videoId);
            client.getAcsResponse(request);
            return R.ok();

        } catch (ClientException e) {
            e.printStackTrace();
            try {
                throw new Exception("删除视频失败");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return R.error();
        }

    }

    //3  删除多个阿里云端视频
    //参数是多个视频id
    @DeleteMapping("delete-batch")
    public R deleteBatch(@RequestParam("videoIdList") List videoIdList){
        vodService.deleteBenchVideo(videoIdList);
        return R.ok();
    }

    //4  根据视频id获取视频凭证
    @GetMapping("getPlayAuth/{id}")
    public R getPlayAuth(@PathVariable String id){
        String playAuth = "";
        try{
            DefaultAcsClient client = InitObject.initVodClient(ConstantVodUtils.KEY_ID, ConstantVodUtils.KEY_SECRET);
            //创建request和response对象
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            request.setVideoId(id);
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            playAuth = response.getPlayAuth();
        }catch (Exception e){
            e.printStackTrace();
            throw new MyHandler(20001,"获取视频播放凭证失败");
        }
        return R.ok().data("playAuth",playAuth);
    }

}
